import numpy as np
import urllib.request

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data"
response = urllib.request.urlopen(url)
data = response.read().decode('utf-8')

lines = data.strip().split('\n')
wine_data = []
for line in lines:
    values = [float(x) for x in line.split(',')]
    wine_data.append(values)

wine_data = np.array(wine_data)

filtered_data = []
for row in wine_data:
    if row[0] in [1.0, 2.0]:
        filtered_data.append(row)

filtered_data = np.array(filtered_data)
X = filtered_data[:, 1:]
y = filtered_data[:, 0]

print("Wine数据（类别1和2）:")
print(f"数据形状: {X.shape}")
print(f"类别1: {np.sum(y == 1)}, 类别2: {np.sum(y == 2)}")


# PCA实现
def simple_pca(X, n_components=2):
    X_centered = X - np.mean(X, axis=0)

    cov_matrix = np.cov(X_centered.T)

    eigenvalues, eigenvectors = np.linalg.eig(cov_matrix)

    idx = np.argsort(eigenvalues)[::-1][:n_components]
    components = eigenvectors[:, idx]

    X_pca = X_centered.dot(components)

    return X_pca

X_pca = simple_pca(X)

print("\nPCA降维后的两维特征（前10个样本）:")
for i in range(10):
    print(f"样本{i + 1}: [{X_pca[i, 0]:.4f}, {X_pca[i, 1]:.4f}]")